package com.sparrow.manage.common.controller;

import com.sparrow.config.EnvironmentVariables;
import com.sparrow.manage.common.entity.Attachment;
import com.sparrow.manage.common.entity.result.EditorUploadImgResult;
import com.sparrow.manage.common.entity.result.Result;
import com.sparrow.manage.util.FileStore;
import com.sparrow.manage.util.NetFileHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 附件上传
 */
@RestController
@RequestMapping(EnvironmentVariables.MANAGE_ACCESS_PREFIX + "/attachment")
public class AttachmentController {

    private static final Logger logger = LoggerFactory.getLogger(AttachmentController.class);

    // 不带/, 相对于项目根目录, 也是运行jar的根目录.
    private static final FileStore fileStore = new FileStore(EnvironmentVariables.FILE_RESOURCE_ROOT);

    /**
     * 最大图片大小(单位:kb)
     */
    private static final int MAX_IMG_SIZE = 1000;

    /**
     * 上传图片
     * @return
     */
    @RequestMapping("/uploadImgWithoutInsert")
    public Result uploadFileImgNoInsert(@RequestParam("file") MultipartFile uploadFile){
        Result result = new Result();
        try {
            String contentType = uploadFile.getContentType();
            InputStream inputStream = uploadFile.getInputStream();
            long size = uploadFile.getSize();
            double quality = MAX_IMG_SIZE / (size / 1024d);
            if(quality < 1){  // 如果上传图片尺寸大于500k, 压缩图片
                ByteArrayOutputStream outputStream = NetFileHandler.compressImage(uploadFile.getInputStream(), quality);
                inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            }
            String filePath = "/" + EnvironmentVariables.FILE_ACCESS_PREFIX + "/" + fileStore.saveFile(inputStream, uploadFile.getOriginalFilename());

            Attachment attr = new Attachment();
            attr.setLocation(filePath);
            attr.setName(uploadFile.getOriginalFilename());
            attr.setSize(NetFileHandler.getFileSizeToDouble(inputStream));
            attr.setContentType(contentType);

            result.setSuccess(true);
            result.setObj(attr);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 仅上传, 不记录到数据库
     * @return
     */
    @RequestMapping("/uploadWithoutInsert")
    public Result uploadFileNoInsert(@RequestParam("file") MultipartFile uploadfile){
        Result result = new Result();
        try {
            String contentType = uploadfile.getContentType();
            String filePath = "/" + EnvironmentVariables.FILE_ACCESS_PREFIX + "/" + fileStore.saveFile(uploadfile.getInputStream(), uploadfile.getOriginalFilename());
            Attachment attr = new Attachment();
            attr.setLocation(filePath);
            attr.setName(uploadfile.getOriginalFilename());
            attr.setSize(NetFileHandler.getFileSizeToDouble(uploadfile));
            attr.setContentType(contentType);

            result.setSuccess(true);
            result.setObj(attr);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 仅上传, 不记录到数据库
     * @return
     */
    @RequestMapping("/uploadFile")
    public EditorUploadImgResult uploadFile(MultipartFile file){
        EditorUploadImgResult result = new EditorUploadImgResult();
        try {
            String fileName = file.getOriginalFilename();
            String filePath = "/" + EnvironmentVariables.FILE_ACCESS_PREFIX + "/" + fileStore.saveFile(file.getInputStream(), fileName);

            result.setFileName(fileName);
            result.setImgUrl(filePath);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            result.setMsg(e.getMessage());
        }
        return result;
    }

}
